package com.ceo.auth.jwt;

import cn.hutool.crypto.digest.MD5;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.ceo.auth.constants.AucConstants;
import com.ceo.common.http.exception.PlatformException;
import com.ceo.common.http.response.DefaultResponse;
import com.ceo.common.utils.CommonContextUtil;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 * @Create by uto_dev_007
 * @Date 2021/11/25 17:43
 */
public class JwtUtil {

    private static Log logger = LogFactory.get();

    /**
     * 生成 token
     */
    public static String createToken(JwtEntity jwtEntity) {
        Date date = new Date(System.currentTimeMillis() + CommonContextUtil.getBean(JwtConfig.class).getExpire());
        Algorithm algorithm = Algorithm.HMAC256(CommonContextUtil.getBean(JwtConfig.class).getSecret());
        // 附带user信息
        return JWT.create()
                .withClaim("id", jwtEntity.getId())
                .withClaim("userId", jwtEntity.getUserId())
                .withClaim("userName", jwtEntity.getUserName())
                .withClaim("client", jwtEntity.getClient())
                //到期时间
                .withExpiresAt(date)
                //创建一个新的JWT，并使用给定的算法进行标记
                .sign(algorithm);
    }

    /**
     * 校验 token 是否正确
     */
    public static boolean verify(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(CommonContextUtil.getBean(JwtConfig.class).getSecret());
            JWTVerifier verifier = JWT.require(algorithm).build();
            //验证 token
            verifier.verify(token);
            return true;
        } catch (Exception exception) {
            return false;
        }
    }

    /**
     * 获得token中的信息，无需secret解密也能获得
     */
    public static JwtEntity getJWTEntity(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return new JwtEntity(
                    jwt.getClaim("id").asString(),
                    jwt.getClaim("userId").asString(),
                    jwt.getClaim("userName").asString(),
                    jwt.getClaim("client").asString());
        } catch (Exception e) {
            throw new PlatformException("Token解析异常");
        }
    }

    public static String getMD5Pwd(String password) {
        return MD5.create().digestHex(password + CommonContextUtil.getBean(JwtConfig.class).getSalt(), "UTF-8");
    }

    public static boolean checkPwd(String pwd, String md5Pwd) {
        return md5Pwd.equals(MD5.create().digestHex(pwd + CommonContextUtil.getBean(JwtConfig.class).getSalt(), "UTF-8"));
    }

    public static void responseState(int status, ServletResponse response) {
        ((HttpServletResponse) response).setStatus(status);
        AucConstants constants;
        switch (status) {
            case 401:
                constants = AucConstants.RESULT_CONSTANTS_SERVER_ERROR_AUTHENTICATION;
                break;
            case 403:
                constants = AucConstants.RESULT_CONSTANTS_SERVER_ERROR_AUTHORIZATION;
                break;
            default:
                constants = AucConstants.RESULT_CONSTANTS_SERVER_ERROR;
                break;
        }
        try {
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;
            httpServletResponse.setCharacterEncoding("UTF-8");
            httpServletResponse.getWriter().write(JSON.toJSONString(DefaultResponse.error(constants.getCode(), constants.getText())));
        } catch (IOException e) {
            logger.error(e.getMessage());
        }
    }

    protected static boolean checkHead(ServletRequest request) {
        HttpServletRequest req = (HttpServletRequest) request;
        String token = req.getHeader("Authorization");
        return token != null;
    }


}
